//
//  NSString+FWPowerful.m
//  iOSToolkit
//
//  Created by Evan Xie on 9/17/14.
//  Copyright (c) 2014 Family Wings. All rights reserved.
//

#import <MobileCoreServices/MobileCoreServices.h>
#import <CommonCrypto/CommonDigest.h>

#import "NSString+FWPowerful.h"


@implementation NSString (FWPowerful)

- (NSString *)MIMEType
{
    NSString *pathExtension = [self pathExtension];
    
    // The UTI can be converted to a MIME type:
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)pathExtension, NULL);
    if (UTI == NULL) return nil;
    
    CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType);
    CFRelease(UTI);
    
    NSString *MIMETypeString = (__bridge_transfer NSString *)MIMEType;
    
    return MIMETypeString;
}

@end


@implementation NSString (Cryptography)

- (NSString *)MD5
{
    // Create pointer to the string as UTF8
    const char *ptr = [self UTF8String];
    
    // Create byte array of unsigned chars
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    
    // Create 16 byte MD5 hash value, store in buffer
    CC_MD5(ptr, (uint32_t)strlen(ptr), md5Buffer);
    
    // Convert MD5 value in the buffer to NSString of hex values
    NSMutableString *md5String = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for (NSUInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
        [md5String appendFormat:@"%02x", md5Buffer[i]];
    }
    
    return md5String;
}

@end
